/**
 * 云端游戏记录状态管理 Store
 */

import { defineStore } from 'pinia';
import { ref } from 'vue';
import { GameScoresService, type GameScore, type ScoresResponse } from '@/services/game-scores.service';
import { useAuthStore } from './auth';

export const useCloudScoresStore = defineStore('cloudScores', () => {
  // State
  const scores = ref<GameScore[]>([]);
  const bestScore = ref<GameScore | null>(null);
  const isLoading = ref<boolean>(false);
  const error = ref<string | null>(null);
  const totalCount = ref<number>(0);
  const currentPage = ref<number>(1);
  const pageSize = ref<number>(20);

  const authStore = useAuthStore();

  // Actions
  /**
   * 提交游戏分数到云端
   */
  async function submitScore(data: {
    score: number;
    correctCount: number;
    wrongCount: number;
    comboMax: number;
    accuracy: number;
    wpm: number;
    duration: number;
    caseSensitive?: boolean;
  }) {
    if (!authStore.isAuthenticated) {
      throw new Error('请先登录');
    }

    try {
      isLoading.value = true;
      error.value = null;
      
      const result = await GameScoresService.submitScore(data);
      
      // 提交成功后刷新列表
      await fetchScores();
      await fetchBestScore();
      
      return result;
    } catch (e: any) {
      error.value = e.message || '提交分数失败';
      throw e;
    } finally {
      isLoading.value = false;
    }
  }

  /**
   * 获取游戏记录列表
   */
  async function fetchScores(page: number = 1) {
    if (!authStore.isAuthenticated) {
      return;
    }

    try {
      isLoading.value = true;
      error.value = null;
      
      const response: ScoresResponse = await GameScoresService.getScores(page, pageSize.value);
      
      scores.value = response.data;
      totalCount.value = response.total;
      currentPage.value = response.page;
    } catch (e: any) {
      error.value = e.message || '获取游戏记录失败';
    } finally {
      isLoading.value = false;
    }
  }

  /**
   * 获取最佳记录
   */
  async function fetchBestScore() {
    if (!authStore.isAuthenticated) {
      return;
    }

    try {
      isLoading.value = true;
      error.value = null;
      
      bestScore.value = await GameScoresService.getBestScore();
    } catch (e: any) {
      // 如果没有记录，不显示错误
      if (e.message.includes('暂无游戏记录')) {
        bestScore.value = null;
      } else {
        error.value = e.message || '获取最佳记录失败';
      }
    } finally {
      isLoading.value = false;
    }
  }

  /**
   * 删除游戏记录
   */
  async function deleteScore(id: number) {
    if (!authStore.isAuthenticated) {
      throw new Error('请先登录');
    }

    try {
      isLoading.value = true;
      error.value = null;
      
      await GameScoresService.deleteScore(id);
      
      // 删除成功后刷新列表
      await fetchScores(currentPage.value);
      
      // 如果删除的是最佳记录，重新获取
      if (bestScore.value?.id === id) {
        await fetchBestScore();
      }
    } catch (e: any) {
      error.value = e.message || '删除记录失败';
      throw e;
    } finally {
      isLoading.value = false;
    }
  }

  /**
   * 清除错误
   */
  function clearError() {
    error.value = null;
  }

  /**
   * 重置状态
   */
  function reset() {
    scores.value = [];
    bestScore.value = null;
    error.value = null;
    totalCount.value = 0;
    currentPage.value = 1;
  }

  /**
   * 初始化
   */
  async function init() {
    if (authStore.isAuthenticated) {
      await fetchScores();
      await fetchBestScore();
    }
  }

  return {
    // State
    scores,
    bestScore,
    isLoading,
    error,
    totalCount,
    currentPage,
    pageSize,
    // Actions
    submitScore,
    fetchScores,
    fetchBestScore,
    deleteScore,
    clearError,
    reset,
    init,
  };
});
